<?php
/*
 * This library is free software; you can redistribute it and/or modify it 
 * under the terms of the BSD License.
 *
 * This library is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
 *
 */

/**
 * A Google Checkout Discount.
 *
 * @package GoogleCheckout
 * @author Byrne Reese <byrne@majordojo.com>
 * @copyright 2006-2008, Byrne Reese.
 */

/**
 * The Discount class is used to retrieve a Discount object from your 
 * database. 
 *
 * @package GoogleCheckout
 */
class Discount {
  public $id;
  public $code;
  public $description;
  public $percentOff;
  public $amountOff;
  public $redeemLimit;
  public $redeemCount;

  private static $BASE_SQL = "SELECT discount_id,code,description,percent_off,amount_off,redeem_limit,redeem_count FROM discounts ";

  public static function findById($id) {
    $d = new Discount();
    $sql = Discount::$BASE_SQL . "WHERE discount_id = $id";
    $query = mysql_query($sql) or die("Error: $sql<p>" . mysql_error());
    if (mysql_num_rows($query) > 0) { 
      list($d->id, $d->code, $d->description, $d->percentOff, $d->amountOff, $d->redeemLimit, $d->redeemCount) = mysql_fetch_row($query);
    } else {
      return;
    }
    return $d;
  }

  public static function findByCode($code) {
    $d = new Discount();
    $sql = Discount::$BASE_SQL . "WHERE code = '$code'";
    $query = mysql_query($sql) or die("Error: $sql<p>" . mysql_error());
    if (mysql_num_rows($query) > 0) { 
      list($d->id, $d->code, $d->description, $d->percentOff, $d->amountOff, $d->redeemLimit, $d->redeemCount) = mysql_fetch_row($query);
    } else {
      return;
    }
    return $d;
  }

  public function isRedeemable() {
    if ($this->redeemLimit == 0) { return 1; } // 0 == Unlimited
    if ($this->redeemLimit > $this->redeemCount) { return 1; }
    return 0;
  }

  public function apply($amount) {
    if ($this->percentOff) {
      return sprintf("-%.2f",($amount * ($this->percentOff / 100)));
    }
    if ($this->amountOff) {
      return "-". ($amount - $this->amount);
    }
    return 0;
  }

  public function redeem() {
    global $TESTRUN_DB;
    $this->redeemCount++;
    $sql = sprintf("UPDATE $TESTRUN_DB.discounts SET redeem_count = %d WHERE discount_id = %d",
		   $this->redeemCount,
		   $this->id);
    mysql_query($sql) or die("Error: $sql<p>" . mysql_error());
  }
}
?>